<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('TT.GasChart.Title') }}</view>
      </HeaderLayout>
    </template>

    <view class="container1">
      <view class="topTitle">
        <view class="topTitleChild" :class="{ titleActive: curDataType === 'day' }" @click="selectDataType('day')">{{
          $t('TT.GasChart.Tab.Day.Text')
        }}</view>
        <view
          class="topTitleChild"
          :class="{ titleActive: curDataType === 'month' }"
          @click="selectDataType('month')"
          >{{ $t('TT.GasChart.Tab.Month.Text') }}</view
        >
        <view class="topTitleChild" :class="{ titleActive: curDataType === 'year' }" @click="selectDataType('year')">{{
          $t('TT.GasChart.Tab.Year.Text')
        }}</view>
      </view>
      <view class="gasMain">
        <view class="gasMainChart">
          <ec-canvas id="myChartDomLine" canvas-id="mychart-line" :echarts="echarts" :ec="ecOptions" />
        </view>
        <view class="gasMainBtm">
          <view @click="previousPage" class="page pageLeft" :class="{ dateDisable: !hasPrevious }">
            <image src="@/pages/appliance/static/TT/ic_gasconsumption_arrow_previous.png" class="leftArrow"></image>
            <text>{{ $t('TT.GasChart.PreviousPage.Text') }}</text>
          </view>
          <view @click="nextPage" class="page pageRight" :class="{ dateDisable: !hasNext }">
            <text>{{ $t('TT.GasChart.BackPage.Text') }}</text>
            <image src="@/pages/appliance/static/TT/ic_gasconsumption_arrow_next.png" class="rightArrow"></image>
          </view>
        </view>
        <view class="gasTip">{{ $t('TT.GasChart.Introduce.Text') }}</view>
      </view>
    </view>
  </PageLayout>
</template>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { actionDebounce, showLoading, toPage } from '@/utils/mpHelper'
import { queryNewGasReport } from '@/api/tt'
import type { EcCanvasComponent, EcCanvasOptions } from '@/pages/appliance/TT/ec-canvas/ec-canvas'
import { useEnvStore } from '@/store/env'
import { getEcharts } from '../useEcharts'
import { useI18n } from 'vue-i18n'

const echarts = getEcharts()

const headerStyle = {
  backgroundColor: '#fff',
}

const ecOptions: EcCanvasOptions = {
  lazyLoad: true,
}

const i18n = useI18n()

let myChart: echarts.ECharts | null = null
let symbolSize = 4
let CHART_DATA = [
  ['周一', 0],
  ['周二', 0],
  ['周三', 0],
  ['周四', 0],
  ['周五', 0],
  ['周六', 0],
  ['周七', 0],
]
const LINE_ICON =
  'path:M65.2,37.4L53.7,25.6c-1.1-1.1-2.8-1.1-3.9,0c-1.1,1.1-1.1,2.9,0,3.9l7.3,7.5H20.4l7.3-7.5c1.1-1.1,1.1-2.9,0-3.9c-1.1-1.1-2.8-1.1-3.9,0L12.3,37.4c-0.6,0.6-0.8,1.3-0.8,2.1c0,0.8,0.2,1.5,0.8,2.1l11.6,11.8c1.1,1.1,2.8,1.1,3.9,0c1.1-1.1,1.1-2.9,0-3.9L20.4,42h36.7l-7.3,7.5c-1.1,1.1-1.1,2.9,0,3.9s2.8,1.1,3.9,0l11.6-11.8c0.6-0.6,0.8-1.3,0.8-2.1C66,38.7,65.8,38,65.2,37.4z'

const option = ref({
  grid: {
    top: '20%',
    bottom: '15%',
  },
  xAxis: {
    type: 'category',
    axisLine: {
      show: true,
      onZero: true,
      lineStyle: {
        color: '#65758A',
        opacity: 0.1,
      },
    },
    boundaryGap: false,
    axisTick: {
      show: false,
    },
    axisLabel: {
      show: true,
      interval: 0,
      color: '#4475D5',
      fontSize: 10,
      align: 'center',
      formatter: (value: string, index: any) => {
        return transferDate(value, tempCurDataType.value)
      },
    },
    minorTick: {
      show: false,
    },
    minorSplitLine: {
      show: false,
    },
    splitLine: {
      show: false,
    },
  },
  yAxis: {
    show: true,
    name: '单位：m³',

    // offset:-15,
    axisLabel: {
      show: false,
    },
    axisLine: {
      show: true,
      onZero: true,
      lineStyle: {
        color: '#4475D5',
        opacity: 0.1,
      },
    },
    axisTick: {
      show: false,
    },
    nameGap: 5,
    nameTextStyle: {
      color: '#4475D5',
      fontSize: 10,
      padding: [0, 0, 0, 55],
    },
    splitLine: {
      show: false,
    },
  },
  series: [
    {
      id: 'a',
      type: 'line',
      smooth: false,
      symbol: LINE_ICON,
      label: {
        normal: {
          show: true,
          position: 'top',
          // formatter: (item) => {
          //   return Math.round(item.value[1] * 2) / 2;
          // },
          fontSize: 10,
          color: '#4475D5',
        },
      },
      symbolSize,
      data: CHART_DATA,
      animation: false,
      clip: true,
      areaStyle: {
        normal: {
          // color: 'rgba(60, 160, 220, 0.1)' //改变区域颜色
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(60, 160, 220,0.39)',
            },
            {
              offset: 0.34,
              color: 'rgba(60, 160, 220,0.25)',
            },
            {
              offset: 1,
              color: 'rgba(60, 160, 220,0.00)',
            },
          ]),
        },
      },
      itemStyle: {
        normal: {
          color: '#4475D5', // 改变折线点的颜色
        },
      },
      lineStyle: {
        color: '#4475D5', // 改变折线颜色
        width: 1,
      },
    },
  ],
})

const haId = ref('')
const tempCurDataType = ref('day')
const curDataType = ref('day')
const hasPrevious = ref(false)
const hasNext = ref(false)
const sourceData = ref([])
const showGasDialog = ref()

onLoad((query: any) => {
  haId.value = query?.haId
})
onShow(async () => {
  let dateTime = new Date()
  curDataType.value = 'day'
  tempCurDataType.value = curDataType.value
  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })
  await queryGasReportFun('day', 'previous', dateTime.toJSON().substr(0, 10))
  await initChart()
  uni.hideLoading()
})
/*
 *查询燃气上报数据
 * @param {*} type
 *   day 日数据
 *   month 月数据
 *   year 年数据
 * @param {*} queryType
 *   previous 上一页
 *   next 下一页
 * @param {*} date （日期）
 */
async function queryGasReportFun(type: string, queryType: string, dateString: string) {
  let payload = {
    data: {
      type: queryType,
      date: dateString,
    },
  }
  const res = await queryNewGasReport(haId.value, type, payload)
  if (res.code === 0) {
    let responseDictData = res.data.gasList
    let newHasPrevious = res.data.hasPrevious
    let newHasNext = res.data.hasNext
    let chartData = []
    for (let i = 0; i < responseDictData.length; i++) {
      let singleData = []
      singleData.push(responseDictData[i]['date'])
      singleData.push(((responseDictData[i]['gas'] * (0.1 * 0.0949 * 10000000)) / 10000000).toFixed(2))
      chartData.push(singleData)
    }
    sourceData.value = JSON.parse(JSON.stringify(chartData))
    option.value.series[0].data = chartData
    if (myChart) {
      myChart.setOption(option.value)
    }
    hasPrevious.value = newHasPrevious
    hasNext.value = newHasNext
  }
}
/**
 * 切换年月日
 * @param type
 */
const selectDataType = actionDebounce({
  loadingText: i18n.t('APP.Common.Loading.Text'),
  call: async (type: string) => {
    curDataType.value = type
    tempCurDataType.value = type
    let dateTime = new Date()
    if (type === 'day') {
      await queryGasReportFun(type, 'previous', dateTime.toJSON().substr(0, 10))
    } else if (type === 'month') {
      dateTime = new Date(dateTime.setMonth(dateTime.getMonth() + 1))
      await queryGasReportFun(type, 'previous', dateTime.toJSON().substr(0, 7))
    } else {
      dateTime = new Date(dateTime.setFullYear(dateTime.getFullYear() + 1))
      await queryGasReportFun(type, 'previous', dateTime.toJSON().substr(0, 4))
    }
  },
})

/**
 * 上一页
 */
const previousPage = actionDebounce({
  loadingText: i18n.t('APP.Common.Loading.Text'),
  call: async () => {
    let dateString = sourceData.value[0][0]
    await queryGasReportFun(curDataType.value, 'previous', dateString)
  },
})

/**
 * 下一页
 */
const nextPage = actionDebounce({
  loadingText: i18n.t('APP.Common.Loading.Text'),
  call: async () => {
    let dateString = sourceData.value[sourceData.value.length - 1][0]
    await queryGasReportFun(curDataType.value, 'next', dateString)
  },
})

/**
 * 初始化图表
 * @param canvas
 * @param width
 * @param height
 */
const instance = getCurrentInstance()
const envStore = useEnvStore()
let ecComponent: EcCanvasComponent | null = null
function initChart() {
  ecComponent = (instance as any).ctx.selectComponent('#myChartDomLine') as EcCanvasComponent | null
  if (!ecComponent) {
    return uni.hideLoading()
  }

  ecComponent.init((canvas, width, height) => {
    /*
     * 获取组件的 canvas、width、height 后的回调函数
     * 在这里初始化图表
     */
    const chart = echarts.init(canvas, void 0, {
      width,
      height,
      devicePixelRatio: envStore.systemInfo.pixelRatio,
    })
    myChart = chart
    myChart.setOption(option.value)
    // wx.hideLoading()

    // 注意这里一定要返回 chart 实例，否则会影响事件处理等
    return chart
  })
}
/**
 * 转化日期
 * @param params
 * @param type
 */
function transferDate(params: string, type: string) {
  let year = params.substr(0, 4)
  let month = params.substr(5, 2)
  let day = params.substr(8, 2)
  if (type === 'year') {
    return year + '年'
  } else if (type === 'month') {
    if (parseInt(month) == 1 || parseInt(month) == 12) {
      return parseInt(month) + '月\n' + year + '年'
    } else {
      return parseInt(month) + '月'
    }
  } else {
    return parseInt(month) + '月' + parseInt(day) + '日'
  }
}
</script>
<style scoped lang="less">
.container1 {
  position: absolute;
  width: 100vw;
  min-height: 100vh;
  background: #f4f4f4;
  text-align: center;
  box-sizing: border-box;
}

.topTitle {
  height: 80rpx;
  background: #fff;
  padding: 0 112rpx;
  display: flex;
  justify-content: space-between;
}

.topTitleChild {
  width: 120rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  color: #65758a;
  font-size: 32rpx;
}

.titleActive {
  border-bottom: 6rpx solid #4475d5;
  color: #4475d5;
}

.gasMain {
  margin: 20rpx 40rpx;
  background: #fff;
  border-radius: 20rpx;
  height: 826rpx;
}

.gasMainTop {
  display: flex;
  padding: 30rpx 32rpx 0 40rpx;
  justify-content: space-between;
  margin: 0 0 86rpx;
}

.gasMainTopLeft {
  color: #4475d5;
  font-size: 28rpx;
}

.gasMainTopLeft text {
  font-size: 28rpx;
}

.gasMainTopRight {
  display: flex;
  width: 172rpx;
  height: 60rpx;
  font-size: 26rpx;
  border-radius: 8rpx;
  border: 2rpx solid #4475d5;
}

.gasMainTopRight view {
  flex: 1;
  line-height: 60rpx;
  text-align: center;
  color: #4475d5;
}

.mainSelect {
  color: #fff !important;
  background: #4475d5;
}

.gasMainTopRight view:nth-child(1) {
  border-right: 2rpx solid #4475d5;
}

.gasMainChart {
  height: 530rpx;
  overflow: hidden;
}
.page {
  height: 80rpx;
  line-height: 80rpx;

  box-sizing: border-box;
}
.pageLeft {
  padding-right: 40rpx;
}
.pageRight {
  padding-left: 40rpx;
}
.gasMainBtm {
  display: flex;
  justify-content: space-between;
  padding: 0 43rpx;
  text-align: left;
}

.dateDisable {
  /* color: #ccc !important; */
  opacity: 0.3;
  pointer-events: none;
}

.gasMainBtm text {
  font-size: 32rpx;
  font-weight: 500;
  color: #3c3c3c;
}

.gasTip {
  font-size: 24rpx;
  color: #b3bac4;
  padding: 0 40rpx;
  margin: 60rpx 0 0;
  text-align: left;
}

.leftArrow {
  width: 16rpx;
  height: 24rpx;
  margin: 0 8rpx 0;
}

.rightArrow {
  width: 16rpx;
  height: 24rpx;
  margin: 0 8rpx 0;
}
</style>
